<?php
/**
 * 离职流程
 */
apf_require_controller("Abstract");
apf_require_class("Bll_Flow_Dimission");
apf_require_class("Bll_Flow_Info");
apf_require_class("Bll_Hr_Property");
class Flow_DimissionController extends AbstractController {

    private $flow_id =0;

    private $flow_data = array();
    private $base_data = array();

    private $flow_bll = null;
    private $log_bll = null;
    private $dimiss_bll = null;
    private $hroa_bll = null;

    public function handle_request() {
        $params = $this->request->get_parameters();
        $flow_id = empty($params['flow_id']) ? 0 : intval($params['flow_id']);
        if(!$flow_id){
            $this->show_tips('ERROR_PARAM');
        }
        $this->flow_bll = new Bll_Flow_Info();
        $flow_data = $this->flow_bll->find_by_id($flow_id);
        if(empty($flow_data)){
            $this->show_tips('ERROR_PARAM');
        }
        //如果是待处理过来同时还是自己
        if($params['view']==1 && $flow_data['flow_stage']==Const_Flow::FLOW_DIMISSION_2 && $flow_data['user_id']== $this->user_info['user_id']){
            $this->response->redirect(Flow_Urls::dimission().'?flow_id='.$flow_id,false,false);exit;
        }
        $this->dimiss_bll = new Bll_Flow_Dimission();
        $base_data = $this->dimiss_bll->find_by_flow_id($flow_id);

        $flow_data['flow_stage'] +=1;
        $check_view = $this->_check_read_flow_auth($flow_data['work_city_id'],$flow_data['flow_type'],$flow_data['flow_stage'],$flow_id);
        if(!$check_view){
            //$this->show_tips('ERROR_PARAM');
        }
        if($params['view']==1){//TODO
            $flow_data['flow_stage'] -=1;
        }

        //还在进行中的
        $base_data['is_allow_opt'] = $this->_check_auth($flow_data['work_city_id'],$flow_data['flow_type'],$flow_data['flow_stage'],$flow_id);

        $base_data['is_close'] = 0;
        if($flow_data['now_status']==2 || $flow_data['now_status']==3 || $flow_data['now_status']==4){//TODO const
            $base_data['is_close'] = 1;
        }

        $this->base_data = array_merge($base_data,$flow_data);

        $this->hroa_bll = new Bll_Hr_OutInterface();

        $userdata = $this->hroa_bll->get_user_base_info($base_data['user_id'],1);
        //检测是否有下级
        $has_sub = $this->hroa_bll->get_subordinate($base_data['user_id']);
        $this->base_data['has_sub'] = empty($has_sub) ? 0 : 1;
        $this->base_data['is_hr'] = isset($this->user_info['role_list'][Const_Flow::ROLE_HR]) ? 1 : 0;
        $this->base_data['is_self'] = $base_data['user_id']==$this->user_info['user_id'] ? 1 : 0;
        //检测是否为技术部
        $this->base_data['is_tech'] = $this->hroa_bll->check_is_tech($userdata['department_id']);
        if($flow_data['now_status']==1){
            $super_data = $this->hroa_bll->get_under_leader($base_data['user_id']);
            $super_uid = empty($super_data) ? 0 : $super_data['user_id'];
            $this->base_data['is_super'] = $super_uid == $this->user_info['user_id'] ? 1 : 0;
        }else{//办理完的就没有职位信息了
            $this->base_data['is_super'] = 0;
            apf_require_class("Bll_Flow_ApplyRelation");
            $bll_rela = new Bll_Flow_ApplyRelation();
            $re = $bll_rela->get_relation($flow_data['flow_id'],array('user_id'=>$this->user_info['user_id']));
            if(!empty($re)){
                $this->base_data['is_super'] = $re['parent_uid']==$this->user_info['user_id'] ? 1 : 0;
            }
        }
        if($this->request->is_post_method()){//POST
            $this->_update_data($params);
            $this->response->redirect(Flow_Urls::flow_list(),false,false);exit;
        }

        $resaon_type = $this->_get_dimiss_type();
        $this->base_data['dimiss_reason'] = $resaon_type['all_reason'];

        $this->base_data['finan_list'] = Const_Flow::finan_list();
        $this->base_data['office_supply'] = Const_Flow::office_supply();
        $this->base_data['hr_confirm_list'] = Const_Flow::hr_confirm();

        $this->base_data['act_reason'] = $resaon_type['act_reason'];
        $this->base_data['passive_reason'] = $resaon_type['passive_reason'];

        $dep_info = $this->hroa_bll->get_job_dep_info($base_data['job_id']);

        $userdata['department_name'] = $dep_info['department_name'];
        $userdata['position_name'] = $dep_info['position_name'];
        $this->request->set_attribute('userdata', $userdata);
        $this->request->set_attribute('myinfo', $this->user_info);
        $this->request->set_attribute('base_data', $this->base_data);
        return "Flow_Dimission";
    }
    /**
     * 提交流程的update动作
     * @param array $params
     * @return boolean
     */
    private function _update_data($params){
        $postdata = $this->_build_post_data($params, $this->base_data['is_allow_opt'],$this->base_data['is_tech']);
        if(empty($postdata)){
            return true;
        }
        $this->_check_params($postdata);//参数检测

        $apply_bll = new Bll_Flow_ApplyRelation();
        $log_bll = new Bll_Flow_OperateLog();

        $plan_date = '';//最后hr确认的离职日期
        $max_opt = 0; //最后一个操作的标志位
        $is_cancel_apply = false;//是否要解除审批关系表记录
        $is_add  = empty($params['view']) ? 1 : 0;//第一次时算增加

        if(in_array($this->base_data['flow_stage'],array(Const_Flow::FLOW_DIMISSION_2,Const_Flow::FLOW_DIMISSION_4)) && $is_add) {
            $is_cancel_apply = true;
        }
        $log_data_tpl = $this->_build_log_data();

        $is_cancel = false;
        //主管驳回/hr撤消 当流程取消
        if($postdata['superior_opinion']==2 || $postdata['hr_opinion']==1){
            $this->flow_bll->update_flow_cancel($this->base_data['flow_id']);
            $is_cancel_apply = true;//审批关系
            $is_cancel = true;
            $hrs_log_data = $log_data_tpl;//取消也写log
            if($postdata['superior_opinion']==2){
                $hrs_log_data['role_type']   = Const_Flow::ROLE_SUPERIOR;
                $hrs_log_data['flow_opt']    = Const_Flow::PHASE_30;
                $hrs_log_data['flow_stage']  = Const_Flow::FLOW_DIMISSION_2;
            }else{
                $hrs_log_data['role_type']   = Const_Flow::ROLE_HR;
                $hrs_log_data['flow_opt']    = Const_Flow::PHASE_37;
                $hrs_log_data['flow_stage']  = Const_Flow::FLOW_DIMISSION_6;
            }
            $log_bll->save_log($hrs_log_data);
            $postdata['now_status'] = 3;
        }else{
            if($postdata['hr_opinion']==2){//流程结束 HR最后一步
                $postdata['now_status'] = 2;
                $postdata['last_date'] = date('Ymd',strtotime($params['last_date']));
                $postdata['leaving_date'] = date('Ymd',strtotime($params['leaving_date']));
                $plan_date = $postdata['leaving_date'];
            }
            //说明财务在操作,如是不是技术部需要直接 跳过操作还图书
            if(isset($postdata['uncleared_type']) && !empty($params['flow_opt']) && in_array(Const_Flow::PHASE_33,$params['flow_opt'])){
                if(!$this->base_data['is_tech'] && $is_add){
                    $in_log_data = $log_data_tpl;
                    $in_log_data['opt_user_id'] = 0;//置用户id为0这条数据不会在列表页展示
                    $in_log_data['role_type']   = Const_Flow::ROLE_BOOK;
                    $in_log_data['flow_opt']    = Const_Flow::PHASE_34;
                    $in_log_data['flow_stage']  = Const_Flow::FLOW_DIMISSION_5;
                    $log_bll->save_log($in_log_data);
                    $max_opt = $in_log_data['flow_opt'];
                }
            }
        }
        //更新基本表
        $this->dimiss_bll->update_leaving($this->base_data['leaving_id'],$postdata);

        //解除上级审批关系
        if($is_cancel_apply){
            $apply_bll->update_by_flow($this->base_data['flow_id']);
        }
        //如果一个人同时具有多个角色，如果填写需要多个log,多个动作对应的角色和阶段 是技术部必须填图片 ，如果选否就不写log
        $is_save_log = false;
        if($this->base_data['is_tech'] && $this->base_data['flow_stage']==Const_Flow::FLOW_DIMISSION_5){
            $is_save_log = true;
        }

        if($is_add){
            $allow_opt_list = $this->_build_opt_to_stage($this->base_data['flow_stage']);
            foreach($params['flow_opt'] as $val){
                if($is_save_log  && $val==Const_Flow::PHASE_34 && $postdata['book_back']==2){
                    continue;
                }
                $max_opt = $val>$max_opt ? $val : $max_opt;
                $log_data = $log_data_tpl;
                $log_data['role_type']   = $allow_opt_list[$val];
                $log_data['flow_opt']    = $val;
                $log_data['flow_stage']  = $this->base_data['flow_stage'];
                $log_bll->save_log($log_data);
            }
        }
        if($is_cancel){
            return true;
        }
        //建立审批关系
        if($this->base_data['flow_stage'] == Const_Flow::FLOW_DIMISSION_3 && $is_add){
            $super_data = $this->hroa_bll->get_under_leader($this->base_data['user_id']);
            $super_uid = empty($super_data) ? 0 : $super_data['user_id'];
            $apply_bll->insert($this->base_data['flow_id'],$this->base_data['user_id'],$super_uid,Const_Flow::FLOW_DIMISSION_4);
        }
        //保存当前操作操作日志,HR最后可能修改时间
        $plan_date = empty($plan_date) ? $this->base_data['plan_date'] : $plan_date;
        $up_flow_log = array(
                'flow_type'  => Const_Flow::FLOW_TYPE_DIMISSION,
                'flow_stage' => $this->base_data['flow_stage'],
                'flow_opt'   => $max_opt,
                'effect_date'=> $plan_date,
                'is_tech'    => $this->base_data['is_tech']
        );

        $status = $this->flow_bll->update_flow($this->base_data['flow_id'],$up_flow_log);
        if($status==4){//离职人员有下级，自动将原有的汇报关系，解除后建立新的
            if($this->base_data['has_sub'] && $this->base_data['after_user_id']){
                $this->_set_job_info($this->base_data['user_id'],$this->base_data['after_user_id']);
            }
            $this->dimiss_bll->sync_user_leaving($this->base_data['user_id'],$postdata['leaving_date'], $postdata['last_date'], $postdata['hr_leaving_type'], $postdata['hr_reason_id'],$this->base_data['other_reason']);
            //清理离职时还有正在待处理的事项
            $this->dimiss_bll->clear_user_flow($this->base_data['user_id']);
        }
        return true;
    }
    /**
     * save log
     * @return multitype:number NULL multitype:
     */
    private function _build_log_data(){
        $log_data_tpl = array(
                'user_id'      => $this->base_data['user_id'],
                'user_name'    => $this->base_data['user_name'],
                'opt_user_id'  => $this->user_info['user_id'],
                'role_type'    => 0,
                'work_city_id' => $this->base_data['work_city_id'],
                'flow_id'      => $this->base_data['flow_id'],
                'flow_opt'     => 0,
                'flow_stage'   => 0,
                'flow_type'    => Const_Flow::FLOW_TYPE_DIMISSION,
                'effect_date'  => $this->base_data['plan_date'],
        );
        return $log_data_tpl;
    }
    /**
     * 设置岗位人选,将离职员工的下级通过岗位继承人建立新关系
     * @param unknown_type $old_uid
     * @param unknown_type $new_uid
     */
    private function _set_job_info($old_uid,$new_uid){
        return $this->hroa_bll->update_user_relation($old_uid,$new_uid);
    }
    /**
     * 各动作所处于的阶段列表
     */
    private function _build_opt_to_stage($stage){
        $flow_list = Const_Flow::flow_to_opt();
        $dimiss_flow = $flow_list[Const_Flow::FLOW_TYPE_DIMISSION];
        $opt_list = array_flip($dimiss_flow[$stage]);
        return $opt_list;
    }
    /**
     * 格式化当前操作可以提交的表单值
     * @param array $params
     * @param int $is_allow_opt
     * @param int $is_tech
     * @return multitype:
     */
    private function _build_post_data($params,$is_allow_opt,$is_tech){
        $updata = array();
        if(empty($is_allow_opt) || empty($params)){
            return $updata;
        }
        $input_list = $this->_build_input_name();
        foreach($is_allow_opt as $opt){
            if (isset($input_list[$opt])) {
                foreach ($input_list[$opt] as $name){
                    if(isset($params[$name])){
                        if(is_array($params[$name])){
                            $updata[$name] = implode(',',$params[$name]);
                        }else{
                            $updata[$name] = $params[$name];
                        }
                    }
                }
            }
        }
        //直属主管审批
        if(isset($updata['superior_opinion'])){
            if($updata['superior_opinion']==2){
                unset($updata['handoff_user_name']);
                unset($updata['handoff_user_id']);
                unset($updata['after_user_name']);
                unset($updata['after_user_id']);
            }else{
                $handoff_user_name = explode('-', $updata['handoff_user_name']);
                $updata['handoff_user_name'] = trim($handoff_user_name[0]);
                if(!empty($updata['after_user_name'])){
                    $after_user_name  = explode('-', $updata['after_user_name']);
                    $updata['after_user_name'] = trim($after_user_name[0]);
                }else{
                    unset($updata['after_user_name']);
                    unset($updata['after_user_id']);
                }
                unset($updata['superior_bak']);
            }
        }
        //交接资料
        //直属主管
        //财务部
        if(isset($updata['uncleared_type'])){
            if($updata['uncleared_type']==0){
                unset($updata['uncleared_text']);//array
                unset($updata['uncleared_money']);
            }
        }
        if(isset($updata['uncleared_sale_type'])){
            if($updata['uncleared_sale_type']==0){
                unset($updata['uncleared_sale_text']);//array
                unset($updata['uncleared_sale_money']);
            }
        }
        //非技术部
        if(!$is_tech){
            unset($updata['book_back']);
            unset($updata['book_bak']);
        }
        //IT部
        //行政部
        //人力资源部
        if(isset($updata['hr_opinion']) && $updata['hr_opinion'] ==1){
            $updata['leaving_date'] = date('Ymd',strtotime($updata['leaving_date']));
            $updata['last_date'] = date('Ymd',strtotime($updata['last_date']));
        }
        if(isset($updata['hr_leaving_type'])){
            $re_id = $updata['hr_leaving_type'] ==1 ? 'hr_reasion_id_1' : 'hr_reasion_id_2';
            $updata['hr_reason_id'] = $updata[$re_id];
            unset($updata['hr_reasion_id_1']);
            unset($updata['hr_reasion_id_2']);
        }
        return $updata;
    }

    /**
     * 操作对应表单的name
     * @return multitype:multitype:string
     */
    private function _build_input_name(){
         return array(
                 30=>array('superior_opinion','handoff_user_name','handoff_user_id','after_user_name','after_user_id','superior_bak'),
                 31=>array('handoff_desc'),
                 32=>array('superior_re_opinion','handoff_re_desc'),
                 33=>array('uncleared_type','uncleared_text','uncleared_money','uncleared_sale_type','uncleared_sale_text','uncleared_sale_money','uncleared_desc','uncleared_bak'),
                 34=>array('book_back','book_bak',),
                 35=>array('close_power','close_bak'),
                 36=>array('callback_type','callback_phone','callback_desc'),
                 37=>array('hr_opinion','option','work_book','hr_checked','hr_bak','hr_leaving_type','hr_reasion_id_1','hr_reasion_id_2'),
           );
    }
    /**
     * 离职类型
     * @return Ambigous <multitype:string , string>
     */
    private function _get_dimiss_type(){
        $bll = new Bll_Hr_Property();
        $data['act_reason'] = $bll->get_active_reason();
        $data['passive_reason'] = $bll->get_passive_reason();
        $data['all_reason'] = $data['act_reason'];
        foreach($data['passive_reason'] as $k=>$val){
            $data['all_reason'][$k] = $val;
        }
        return $data;
    }
    private function _check_params($postdata){
        //如果是第二步应该填岗位
        if((empty($postdata['handoff_user_name']) || empty($postdata['handoff_user_id'])) && $postdata['superior_opinion']==1){
            $this->show_tips('ERROR_EMPTY_HANDOFF');
        }
        if($this->base_data['flow_stage'] == Const_Flow::FLOW_DIMISSION_2 && $this->base_data['has_sub'] && $postdata['superior_opinion']==1
                && (empty($postdata['after_user_name']) || empty($postdata['after_user_id']))){
            $goto = Flow_Urls::dimission().'?flow_id='.$this->base_data['flow_id'].'&view=1';
            $this->show_tips('ERROR_HAS_SUB',$goto);
        }
        return true;
    }
}
